import { createRouter, createWebHistory } from 'vue-router'
import AppLayout from "@/components/Layout/AppLayout.vue";
import Course from "@/views/course/Course.vue";
import Home from "@/views/home/Home.vue";
import CourseDetail from "@/views/course/CourseDetail.vue";
import Teacher from "@/views/teacher/Teacher.vue";
import Login from "@/views/login/Login.vue";
import {useUserStore} from "@/stores/user.js";
import CourseDetails from "@/views/course/CourseDetails.vue";
import User from "@/views/user/User.vue";


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'appLayout',
      component: AppLayout,
      redirect: '/home',
      children:[
        {
          path: 'home',
          name: 'home',
          component: Home
        },
        {
          path: 'course',
          name: 'course',
          component: Course
        },
        {
          path: 'course/:id',
          name: 'courseDetail',
          component: CourseDetails
        },
        {
          path: 'teacher',
          name: 'teacher',
          component: Teacher
        },
        {
          path: 'user',
          name: 'user',
          component: User
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    }
  ]
})
const whiteList = ['/login']; // 定义白名单

// 全局路由守卫
router.beforeEach((to, from, next) => {
  // to：跳转的路由对象
  // from：从哪里来
  // next：放行next() 重定向next(路径)
  const authStore = useUserStore(); // 获取 authStore 实例
  const hasToken = !!authStore.getToken(); // 检查是否有 token

  if (hasToken) {
    // 如果有 token
    if (to.path === '/login') {
      // 如果目标路由是登录页面，重定向到首页
      next('/');
    } else {
      // 如果不是登录页面，允许访问
      next();
    }
  } else {
    // 如果没有 token
    if (whiteList.includes(to.path)) {
      // 如果目标路由在白名单中，允许访问
      next();
    } else {
      // 如果目标路由不在白名单中，重定向到登录页面
      next('/login');
    }
  }
});
export default router
